import { INodeStruct } from './types';
import './node.less';
import { CaretRightOutlined, CaretDownOutlined } from '@ant-design/icons';
import { useState, useContext, PropsWithChildren, ReactNode } from 'react';
import { TreeProvider } from './tree-provider';

export function Node(props: { data: INodeStruct<any>, className?: string, renderChildren?: (node: INodeStruct<any>) => ReactNode }) {
    let [isOpen, setIsOpen] = useState(props.data.isOpen);
    function changeOpenStatus() {
        setIsOpen(!isOpen);
        props.data.isOpen = !isOpen;
    }
    let { onNodeClick } = useContext(TreeProvider);
    let child: ReactNode = (<></>);
    if (props.renderChildren) {
        child = props.renderChildren(props.data);
    }
    return (
        <div className="spd-tree-node" key={props.data.id}>
            <div className="spd-tree-node-content">
                <div className="spd-tree-node-prefix">
                    {props.data.children.length > 0 ? (<span onClick={changeOpenStatus}>{isOpen ? <CaretDownOutlined /> : <CaretRightOutlined />}</span>) : (<>&nbsp;</>)}
                </div>
                <div className={'spd-tree-node-name ' + props.className + (props.data.isActive ? ' spd-tree-node-active' : '')}>
                    <span onClick={() => {
                        onNodeClick(props.data.data, props.data);
                        // props.data.isActive = !props.data.isActive;
                    }} className="spd-tree-node-name-text">&nbsp;{props.data.name}</span>
                    {child}
                </div>
            </div>
            {isOpen ? (
                <div className="spd-tree-node-children">
                    <Nodes datas={props.data.children} className={props.className} renderChildren={props.renderChildren}></Nodes>
                </div>
            ) : ''}
        </div>
    );
}
export function Nodes(props: { datas: INodeStruct<any>[], className?: string, renderChildren?: (node: INodeStruct<any>) => ReactNode }) {
    let className = props.className ? props.className : '';
    return (
        <>
            {props.datas.map(item => {
                return (<Node data={item} key={item.id} className={className} renderChildren={props.renderChildren}></Node>)
            })}
        </>
    );
}


